package com.expense.app.admin.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.expense.app.admin.annotation.IgnoreAuth;
import com.expense.app.admin.config.WebMvcConfig;
import com.expense.common.exception.PlatformException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    private static final Log log = LogFactory.get();

    WebMvcConfig webMvcConfig;

    public AuthenticationInterceptor(WebMvcConfig webMvcConfig) {
        this.webMvcConfig = webMvcConfig;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进入过滤器-----------------------------"+request.getRequestURI());
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-Control-Allow-Origin","*");
        httpServletResponse.setHeader("Access-Control-Allow-Methods","GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers",httpServletRequest.getHeader("Access-Control-Request-Headers"));
        httpServletResponse.setHeader("Access-Control-Max-Age","2592000");
        if(httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        IgnoreAuth annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class);
        }else  return true;
        //如果有@IgnoreAuth注解，则不验证token
        if(annotation != null)  return true;

        //从header中获取token
        String token = request.getHeader("token");
//        System.out.println("-----当前Token是---"+token);
        //如果header中不存在token，则从参数中获取token
        if(StrUtil.isBlank(token)) token = request.getParameter("token");
        //token为空
        if(StrUtil.isBlank(token))  throw new PlatformException("token失效");
        return true;
    }
}
